<?php

namespace addons\qingdong\library;

use addons\qingdong\model\AdminConfig;
use addons\qingdong\model\Staff;
use EasyWeChat\Factory;
use think\Cache;
use think\Model;
use fast\Http;

/**
 * 企业微信
 */
class WechatEnterprise
{
    public $config;
    public $error;
    protected $app;
    public $corpid;
    public $corpsecret;
    public function __construct()
    {
        $this->corpid = AdminConfig::getConfigValue('corpid', 'wechat');
        $this->corpsecret = AdminConfig::getConfigValue('corpsecret', 'wechat');
    }

    //获取企业微信userid
    public function userid($mobile)
    {
        $user = array(
            'mobile' => $mobile,
        );
        $access_token=$this->get_token();
        $url = 'https://qyapi.weixin.qq.com/cgi-bin/user/getuserid?access_token=' . $access_token;
        $customer = $this->http_post($url, json_encode($user));
        $result = json_decode($customer, true);
        if ($result['errcode'] == 0) {
            $staffinfo = Staff::where(['mobile' => $mobile])->find();
            if (!$staffinfo) {
                $this->error = '员工手机号不存在';
                return false;
            }
            Staff::where(['mobile' => $mobile])->update(['touser' => $result['userid']]);
            return $result['userid'];
        }
        return false;
    }

    //获取token
    public function get_token()
    {
        $access_token = Cache::get('enterprise_access_token');
        if (empty($access_token)) {
            $url = 'https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=' . $this->corpid . '&corpsecret=' . $this->corpsecret;
            $token = $this->http_get($url);
            $token = json_decode($token, true);
            if ($token['errcode'] != 0) {
                return false;
            }
            $access_token = $token['access_token'];
            $this->access_token = $token['access_token'];
            Cache::set('enterprise_access_token', $access_token, 6000);
        }
        return $access_token;
    }

    /**
     * curl请求
     */
    private function http_post($url, $param, $post_file = false)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, false);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        if (is_string($param) || $post_file) {
            $strPOST = $param;
        } else {
            $aPOST = array();
            foreach ($param as $key => $val) {
                $aPOST[] = $key . "=" . urlencode($val);
            }
            $strPOST = join("&", $aPOST);
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($oCurl, CURLOPT_POST, true);
        curl_setopt($oCurl, CURLOPT_POSTFIELDS, $strPOST);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }

    /**
     * 发送模板
     */
    public function sendTemplate($touser,$data)
    {
        $miniAppid = AdminConfig::getConfigValue('mini_appid', 'wechat');
        $web_url = AdminConfig::getConfigValue('web_url', 'wechat');
        $agentid = AdminConfig::getConfigValue('agentid', 'wechat');

        if (!empty($miniAppid)) {//打开小程序页面
            if(!$data['description']){
                $data['description'] = '消息通知信息';
            }
            $user = array(
                'touser' => $touser,
                'msgtype' => 'miniprogram_notice',
                'miniprogram_notice' => array(
                    'appid' => $miniAppid,
                    "page" => 'pages/index/index',
                    "emphasis_first_item" => false,
                    "title" => $data['title'],
                    "description" => isset($data['description']) ?$data['description'] :'消息通知信息',
                    "content_item" => $data['content_item'],
                ),
                "enable_id_trans" => 0,
                "enable_duplicate_check" => 0,
                "duplicate_check_interval" => 0
            );

        } else {
            if(!$data['description']){
                $data['description'] = '消息通知信息';
            }
            $user = [
                'touser' => $touser,
                'msgtype' => 'textcard',
                'agentid' =>$agentid,
                'textcard'=>[
                    'title' => $data['title'],
                    'description' => $data['description'],
                    'url' => cdnurl('/h5/#/pages/index/index',true),
                ]
            ];

        }

        $url = 'https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=' . $this->get_token();
        $result = $this->httpPost($url, $user);
        $result = json_decode($result, true);

        if ($result['errcode'] != 0) {
            $this->error = $result['errmsg'];
            return false;
        }
        return true;
    }

    /**
     * post请求
     * @param $url
     * @param string $param
     * @return bool|string
     */
    public function httpPost($url, $param = '')
    {

        if (empty($url) || empty($param)) {
            return false;
        }
        if (is_array($param)) {
            $param = json_encode($param);
        }
        $postUrl = $url;
        $curlPost = $param;
        $ch = curl_init(); //初始化curl
        curl_setopt($ch, CURLOPT_URL, $postUrl); //抓取指定网页
        curl_setopt($ch, CURLOPT_HEADER, 0); //设置header
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_POST, 1); //post提交方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $curlPost);

        $headers = array();
        $headers[] = 'Content-Type: text/plain';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch); //运行curl
        curl_close($ch);
        return $result;
    }

    /**
     * curl请求
     */
    private function http_get($url)
    {
        $oCurl = curl_init();
        if (stripos($url, "https://") !== FALSE) {
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($oCurl, CURLOPT_SSL_VERIFYHOST, FALSE);
            curl_setopt($oCurl, CURLOPT_SSLVERSION, 1); //CURL_SSLVERSION_TLSv1
        }
        curl_setopt($oCurl, CURLOPT_URL, $url);
        curl_setopt($oCurl, CURLOPT_RETURNTRANSFER, 1);
        $sContent = curl_exec($oCurl);
        $aStatus = curl_getinfo($oCurl);
        curl_close($oCurl);
        if (intval($aStatus["http_code"]) == 200) {
            return $sContent;
        } else {
            return false;
        }
    }


}
